package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.his.po.Department;
import com.neuedu.his.service.DepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 科室管理接口
 */
@RestController
@RequestMapping("/api/master/dept")
public class DeptController {

    @Autowired
    private DepartmentService deptService;

    // ============================== 查询 ==============================

    /**
     * 分页 + 关键字查询
     * 示例：GET /api/master/dept?keyword=GNK&page=1&pageSize=10
     */
    @GetMapping
    public IPage<Department> page(
            @RequestParam(defaultValue = "1") long page,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestParam(required = false) String keyword
    ) {
        Page<Department> pg = new Page<>(page, pageSize);
        LambdaQueryWrapper<Department> qw = new LambdaQueryWrapper<>();

        // 同时按名称 / 编码模糊匹配
        if (StringUtils.isNotBlank(keyword)) {
            qw.and(q -> q
                    .like(Department::getDeptname, keyword)   // 科室名称
                    .or()
                    .like(Department::getDeptcode, keyword)   // 科室编码
            );
        }

        // 逻辑删除：delmark = 1 表示有效
        qw.eq(Department::getDelmark, 1);

        return deptService.page(pg, qw);
    }

    /**
     * 根据 ID 查询
     * GET /api/master/dept/{id}
     */
    @GetMapping("/{id}")
    public Department getById(@PathVariable Integer id) {
        return deptService.getById(id);
    }

    // ============================== 新增 / 修改 ==============================

    /**
     * 新增科室
     * POST /api/master/dept
     */
    @PostMapping
    public boolean save(@RequestBody Department dept) {
        dept.setDelmark(1);           // 新增默认有效
        return deptService.save(dept);
    }

    /**
     * 更新科室
     * PUT /api/master/dept/{id}
     */
    @PutMapping("/{id}")
    public boolean update(@PathVariable Integer id,
                          @RequestBody Department dept) {
        dept.setId(id);
        return deptService.updateById(dept);
    }

    // ============================== 逻辑删除 ==============================

    /**
     * 逻辑删除
     * DELETE /api/master/dept/{id}
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        Department tmp = new Department();
        tmp.setId(id);
        tmp.setDelmark(0);            // 0 = 已删除
        return deptService.updateById(tmp);
    }
}
